//右滑关闭
mui.init({
	swipeBack: true,
})
var counts = "";
var UserNO = localStorage.getItem("UserNO");
// 储存临时计算的库存条码
var StockList = []; // 每个元素格式: { BarCodeNO: "条码编号" }

mui.plusReady(function() {
	GetSingOrder();
	BandCode();
	$("#BarCode").focus();
	plus.nativeUI.closeWaiting();
})


//初始化显示
function GetSingOrder() {
	WarehouseList();
	$("#BarCode").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {
			var BarCode = $("#BarCode").val();
			if (BarCode.indexOf("||") !== -1) { // 或者用 includes("||")
				BarCode = BarCode.split("||")[0];
				//console.log("解析到的条码:", firstBarcode); 
			}
			$("#BarCode").val(BarCode);
			// 发送请求
			xccFormPostAsync("api/PDA/QueryMaterialInfo", {
				BarcodeNO: BarCode

			}, function(data) {
				document.activeElement.blur();
				if (data.Code === 200) {
					$("#MaterialCode").val(data.Items[0].MaterialNO);
					$("#BarCode").val('');
					$("#Qty").focus();

				}
				plus.nativeUI.closeWaiting(); // 关闭转圈圈特效
			}, function(error) {
				$("#BarCode").val('');
				$("#BarCode").focus();
				plus.nativeUI.closeWaiting(); // 关闭转圈圈特效
			});

			$("#MaterialCode").focus();
		}
	});

	$("#all").html("");
	$("#all").html(
		'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
		(window.screen.height - 480) + 'px">No data available at the moment</a>');
	StockList = [];
}



function openPosition(BarcodeNO, StockQty) {

	// 显示选择对话框
	showSelectionDialog(BarcodeNO, StockQty);

}

function showSelectionDialog(BarcodeNO, StockQty) {
	// 创建对话框元素
	const dialog = document.createElement('div');
	dialog.className = 'selection-dialog';
	dialog.innerHTML = `
        <p>条码:${BarcodeNO},请选择操作:</p>
        <button class="mui-btn mui-btn-primary" onclick="handleSelection('singleCode','${BarcodeNO}','${StockQty}')">拆包</button>
        <button class="mui-btn mui-btn-danger" onclick="handleSelection('cancel', '${BarcodeNO}', '${StockQty}')">取消</button>
    `;

	// 将对话框添加到 body
	document.body.appendChild(dialog);

	// 添加关闭对话框的事件监听器
	dialog.addEventListener('click', function(event) {
		if (event.target === dialog) {
			dialog.remove();
		}
	});
}

function handleSelection(action, BarcodeNO, StockQty) {
	// 根据选择的操作执行相应的逻辑
	switch (action) {
		case 'cancel':
			console.log('取消操作');
			break;
		case 'singleCode':
			mui.openWindow({
				url: 'WMS_CodeUnpacking.html',
				action: UserName,
				extras: {
					BarcodeNO: BarcodeNO,
					StockQty: StockQty
				}
			});
			break;
	}

	// 移除对话框
	document.querySelector('.selection-dialog').remove();
}


// 更新库存列表显示
function UpdateStockListDisplay() {
	$("#all").html(""); // 清空显示

	if (StockList.length === 0) {
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		return;
	}

	StockList.forEach(item => {
		$("#all").append(
			`<li class="mui-table-view-cell" onclick="openPosition('${item.BarcodeNO}','${item.StockQty}')">
                <div class="list-title">Code:${item.BarcodeNO}&nbsp;&nbsp;&nbspQty:${item.StockQty}</div>
                <div class="list-detail">LampNO:${item.LampNO}&nbsp;&nbsp;&nbspStrNO:${item.StorageNO}</div>
            </li>`
		);
	});
}
//绑定扫码下架
function BandCode() {
	// 绑定 MaterialCode 输入框的 keyup 事件
	$("#BarCode").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {

			var BarCode = $("#BarCode").val();
			// 检查 BarCode 是否为空
			if (!BarCode) {
				mui.toast("Please scan the BarCode。", {
					duration: '1000',
					type: 'div'
				});
				$("#BarCode").focus();
				return;
			}
			if (BarCode.indexOf("||") !== -1) { // 或者用 includes("||")
				BarCode = BarCode.split("||")[0];
				//console.log("解析到的条码:", firstBarcode); 
			}
			$("#BarCode").val(BarCode);
			// 检查条码是否在StockList中
			var index = StockList.findIndex(item => item.BarcodeNO === BarCode);
			if (index === -1) {
				mui.toast("Barcode not found in current stock list", {
					duration: '1000',
					type: 'div'
				});
				Audio();
				$("#BarCode").val('');
				$("#BarCode").focus();
				return;
			}

			var datas = {
				Color: 0,
				LigthCheck: false,
				Items: [{
					BarcodeNO: BarCode
				}]
			};
			var totalStockQty = Number(StockList[index].StockQty);
			var Qty = Number($("#Qty").val());
			// 发送请求
			xccFormPostAsync("api/PDA/AllOffLigthInfo", datas, function(data) {
				document.activeElement.blur();
				if (data.Code === 200) {
					if ((Qty - totalStockQty) <= 0)
						$("#Qty").val(0);
					else
						$("#Qty").val(Qty - totalStockQty);
					// 从StockList中移除已下架的条码
					StockList = StockList.filter(item => item.BarcodeNO !== BarCode);
					// 更新显示
					UpdateStockListDisplay();
					mui.toast("success", {
						duration: '1000',
						type: 'div'
					});
					$("#BarCode").val('');
					$("#BarCode").focus();
				}
			}, function(error) {

			});

		}
	});
}
//全部下架
function AllDown() {
	var ColorNO = $("#shelfOption").val();
	var datas = {
		Color: ColorNO,
		LigthCheck: false,
		Items: StockList
	};
	var totalStockQty = 0;
	var Qty = Number($("#Qty").val());
	xccFormPostAsync("api/PDA/AllOffLigthInfo", datas, function(data) {
		if (data.Code === 200) {
			mui.toast("success ", {
				duration: '1000',
				type: 'div'
			});

			$("#all").html("");
			$("#all").html(
				'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
				(window.screen.height - 480) + 'px">No data available at the moment</a>');
			totalStockQty = StockList.reduce((sum, item) => sum + item.StockQty, 0);
			if ((Qty - totalStockQty) <= 0)
				$("#Qty").val(0);
			else
				$("#Qty").val(Qty - totalStockQty);
			StockList = [];
			$("#Qty").val('');
			$("#MaterialCode").val('');
			$("#BarCode").focus();
		} else {
			mui.toast("error " + data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
	}, function(errr) {})
}

//亮灯
function LigthUP() {
	var ColorNO = $("#shelfOption").val();
	var datas = {
		Color: ColorNO,
		LigthCheck: true,
		Items: StockList
	};
	xccFormPostAsync("api/PDA/QueryLigthInfo", datas, function(data) {
		if (data.Code === 200) {
			mui.toast("success ", {
				duration: '1000',
				type: 'div'
			});
		} else {
			mui.toast("error " + data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
	}, function(errr) {})
}

//灭灯
function LigthOff() {
	var ColorNO = $("#shelfOption").val();
	var datas = {
		Color: ColorNO,
		LigthCheck: false,
		Items: StockList
	};
	xccFormPostAsync("api/PDA/QueryLigthInfo", datas, function(data) {
		if (data.Code === 200) {
			mui.toast("success ", {
				duration: '1000',
				type: 'div'
			});
		} else {
			mui.toast("error " + data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
	}, function(errr) {})
}


// 初始化仓库
function WarehouseList() {
	xccpostAsync("api/PDA/GetWarehouseInfo", {}, function(data) {
		document.activeElement.blur();
		console.log(JSON.stringify(data));
		if (data.Code === 200) {
			data.Items.forEach(item => {
				$("#WarehouseList").append(
					`<option value="${item.WarehouseID}">${item.WarehouseName}</option>`
				);
			});
		} else {
			mui.toast("failed。" + data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
		plus.nativeUI.closeWaiting(); // 关闭转圈圈特效
	}, function(error) {
		console.log("没有数据....");
		plus.nativeUI.closeWaiting(); // 关闭转圈圈特效
	});
}

//获取需要下架的条码
function GetStockList() {
	var html = "";
	var MaterialNO = $("#MaterialCode").val();
	if (!MaterialNO) {
		mui.toast("The material number is empty", {
			duration: '1000',
			type: 'div'
		});
		return false;
	}
	var Qty = $("#Qty").val();
	if (!Qty) {
		mui.toast("The Qty is empty ", {
			duration: '1000',
			type: 'div'
		});
		return false;
	}
	xccFormPostAsync("api/PDA/GetStockList", {
		MaterialNO: MaterialNO,
		Qty: Qty,
		WarehouseID: $("#WarehouseList").val()
	}, function(data) {
		if (data.Items != null && data.Items.length > 0) {
			$("#all").html(""); ////全部清空

			for (var i = 0; i < data.Items.length; i++) {
				var existingIndex = StockList.findIndex(item => item.BarcodeNO === data.Items[i].BarcodeNO);

				if (existingIndex === -1) {
					StockList.push({
						BarcodeNO: data.Items[i].BarcodeNO,
						LampNO: data.Items[i].LampNO,
						LampCode: data.Items[i].LampCode,
						StorageNO: data.Items[i].StorageNO,
						StockQty: data.Items[i].StockQty
					});
				};
			}
			UpdateStockListDisplay();

		}
	}, function(errr) {
		$("#all").html("");
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		StockList = [];
	})
}